from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from routers.auth import auth_router
from routers.admin import admin_router
from routers.llm_create import llm_create_router
from middleware.request_logging import RequestLoggingMiddleware
from dao.redis_connect import RedisClient
from dao.postgresql_connect import check_connection as check_pg_connection
from contextlib import asynccontextmanager
import os
from dotenv import load_dotenv

# 加载环境变量
load_dotenv()

# 获取环境变量
FRONTEND_PROD_URL = os.getenv("FRONTEND_PROD_URL", "http://localhost:3000")
ENV = os.getenv("ENV", "dev")  # 默认为开发环境

# 根据环境确定允许的源
allowed_origins = ["http://localhost:3000", "http://127.0.0.1:3000"] if ENV == "dev" else [FRONTEND_PROD_URL]


@asynccontextmanager
async def lifespan(app: FastAPI):
    """
    应用程序生命周期管理器
    
    这个函数负责：
    1. 检查数据库连接
    2. 设置其他必要的资源
    """
    try:
        # 1. 检查数据库连接
        print("正在检查数据库连接...")
        RedisClient.check_connection()
        check_pg_connection()
        print("✓ 数据库连接检查通过")

        print("应用启动成功！服务已准备就绪")
        yield

        # 应用关闭时的清理代码
        print("正在关闭应用...")
        # 这里可以添加清理代码，比如关闭连接池等

    except Exception as e:
        print(f"启动失败: {str(e)}")
        raise


# 创建FastAPI应用实例
app = FastAPI(
    title="ZKDTech API",
    description="ZKDTech API文档",
    version="1.0.0",
    docs_url="/docs",  # Swagger UI的URL
    redoc_url="/redoc",  # ReDoc的URL
    lifespan=lifespan  # 设置生命周期管理器
)

# 配置CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=allowed_origins,  # 根据环境使用对应的域名
    allow_credentials=True,
    allow_methods=["GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH"],  # 添加 PATCH 方法
    allow_headers=["Content-Type", "Authorization", "X-Requested-With", "Accept", "Origin", "Access-Control-Allow-Origin"],  # 添加更多请求头
    expose_headers=["Content-Type", "Authorization"],  # 暴露响应头
    max_age=600,  # 预检请求缓存时间
)

# 添加请求日志中间件
app.add_middleware(RequestLoggingMiddleware)

# 注册路由
app.include_router(
    auth_router,
    prefix="/api/v1",  # API版本前缀
    tags=["用户认证"]  # API分组标签
)

# 注册管理路由
app.include_router(
    admin_router,
    prefix="/api/v1",  # API版本前缀
    tags=["系统管理"]  # API分组标签
)

# 注册LLM模型路由
app.include_router(
    llm_create_router,
    prefix="/api/v1",  # API版本前缀
    tags=["LLM模型管理"]  # API分组标签
)


# 健康检查接口
@app.get("/", tags=["健康检查"])
async def root():
    return {"message": "服务正常运行"}


if __name__  == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8011)
